<template>
	<view class="baseForm">
		<view class="" style="padding: 15px; border-radius: 15px; color: #fff">
			<u-button @click="lineStoveRecord" style="border-radius: 20px; background-color: #ffbf6b">
				人员出勤填报
			</u-button>
		</view>
		<!-- 当前作业 -->
		<view class="activeHeight" v-if="tableList.length > 0">
			<!-- 列表 -->
			<u-list ref="tableScroll" @scrolltolower="scrolltolower" class="list" :height="listHeight"
				lowerThreshold="50px" :pagingEnabled="true">
				<u-list-item v-for="(item, index) in tableList" :key="item.id">
					<view class="card">
						<view class="flex record-title">
							<text class="line1">填报日期</text>
							<text>
								{{ item.reportDate.split(" ")[0] || "无" }}
							</text>
						</view>
						<view class="flex flex-col justify-between flex-1 h-full record-content-body">
							<view class="record-content">
								<view class="record-item">
									<text>班次</text>
									<text>
										{{ item.shiftName || "无" }}
									</text>
								</view>
								<view class="record-item">
									<text>班组</text>
									<text>
										{{ item.crewName || "无" }}
									</text>
								</view>
								<view class="record-item">
									<text>应出勤人数:{{ item.planNumber || 0}}</text>
									<text>实际出勤人数: {{ item.actualNumber || 0}}</text>
								</view>
								<u-line style="margin: 5px 0 2px" color="#dadbde"></u-line>
								<view style="
										display: flex;
										justify-content: space-between;
									">
									<view style="
											padding: 5px 15px 5px 15px;
											border-radius: 5px;
											color: #ffffff;
											font-size: 12px;
											height: 20px;
											line-height: 20px;
											background-color: #ff7070;
										" @click="deleted(item)">
										删除
									</view>
									<view style="
											padding: 5px 15px 5px 15px;
											border-radius: 5px;
											color: #fff;
											font-size: 12px;
											height: 20px;
											line-height: 20px;
											background-color: #0379ff;
										" @click="openTemperature(item)">
										编辑
									</view>
								</view>
							</view>
						</view>
					</view>
				</u-list-item>
			</u-list>

			<view class="flex justify-center" v-show="tableLoading">
				<u-loading-icon color="#000a7b"></u-loading-icon>
			</view>
		</view>
		<!-- 空数据 -->
		<view v-show="tableList.length === 0 && !tableLoading">
			<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
		</view>
		<u-modal :show="showImportTemperature" ref="uModal1" confirmText="确认" :showCancelButton="true"
			@cancel="cancelImportTemperature" @confirm="confirmImportTemperature">
			<view class="slot-content">
				<u--form labelPosition="left" :model="formData" ref="uForm" :rules="rules" labelWidth="80px"
					errorType="toast">
					<u-form-item label="填报日期" prop="reportDate" @click="openTimeSelectReportDate">
						{{ formData.reportDate.split(" ")[0] }}
						<u--input v-model="formData.reportDate" border="none" disabled v-if="false"
							disabledColor="#ffffff" placeholder="请选择时间"></u--input>
						<u-datetime-picker :show="showReportDate" v-model="formData.reportDateA" mode="date"
							@cancel="showReportDate = false" @confirm="timeSelectReportDate1"></u-datetime-picker>
					</u-form-item>
					<u-form-item label="班次" prop="shiftId" @click="openPickSelect">
						<u--input v-model="formData.shiftName" border="none" disabled disabledColor="#ffffff"
							inputAlign="right" placeholder="请选择班次"></u--input>
						<template #right>
							<u-icon name="arrow-right"></u-icon>
						</template>
					</u-form-item>
					<u-form-item label="班组" prop="shiftId" @click="openPickSelect">
						<u--input v-model="formData.shiftName" border="none" disabled disabledColor="#ffffff"
							inputAlign="right" placeholder="请选择班次"></u--input>
						<template #right>
							<u-icon name="arrow-right"></u-icon>
						</template>
					</u-form-item>
					<u-form-item label="应出勤人数" prop="planNumber">
						<u--input style="height: 20px" v-model="formData.planNumber" class="inputHeight"
							placeholder="应出勤人数" clearable></u--input>
					</u-form-item>
					<u-form-item label="实际出勤人数:" prop="actualNumber">
						<u--input style="height: 20px" v-model="formData.actualNumber" class="inputHeight"
							placeholder="实际出勤人数" clearable></u--input>
					</u-form-item>
				</u--form>
			</view>
		</u-modal>
		<!-- 删除 -->
		<u-modal :show="showImport" ref="uModal"
			:content="`是否删除日期是：${deletedItem?.reportDate?.substring(0,11)}，班次为：${deletedItem?.shiftName}的产线填报记录？`"
			confirmText="确认" showCancelButton @cancel="cancelImport" @confirm="confirmImport"
			:showConfirmButton="showConfirmButton"></u-modal>
		<!-- 班次 -->
		<u-picker :show="showShift" :columns="shiftList" keyName="shiftName" :defaultIndex="shiftIndex" immediateChange
			@cancel="showShift = false" @confirm="shiftSelect"></u-picker>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, toRaw, reactive } from "vue";
	import { onShow, onPullDownRefresh, onLoad } from "@dcloudio/uni-app";
	import { http } from "@/utils/http";
	import { PageResult, TabInfo } from "@/types/type";
	import { getSecondTime, getTimes } from "@/utils/common";
	import { useDictionaryStore } from "@/stores/useDictionaryStore";
	import { useUserStore } from '@/stores/useUserStore';
	import { useProduceStore } from "@/stores/useProduceStore";

	// 实时获取
	const workOrderList = computed(
		() => JSON.parse(useProduceStore().workOrderList) || []
	);
	const crewMemberList = computed(() => JSON.parse(useProduceStore().crewMemberList));
	console.log("crewMemberList", crewMemberList.value[0])
	// 待完成数据
	const tableList = ref([]);
	const tableLoading = ref(false);
	const current = ref(0);
	const totalPage = ref(0);
	const total = ref(0);
	//列表高度
	const listHeight = ref("");

	onShow(() => {
		// #ifdef H5
		listHeight.value = "calc(100vh - 88px)";
		// #endif

		// #ifdef APP-PLUS
		listHeight.value = "calc(100vh - 48px)";
		// #endif
		
		tableList.value = [];
		// 获取列表
		loadmore()
		//获取班次
		// getShiftList();
	});

	onPullDownRefresh(() => {
		uni.stopPullDownRefresh();
	});
	const processesClassification = ref();
	async function loadmore(type ?: string) {
		try {
			current.value += 1;
			tableLoading.value = true;
			const result : PageResult<any> = await http({
				method: "POST",
				url: "/mes/mesattendancereport/queryByPage",
				data: {
					current: current.value,
					size: 20,
					data: {},
				},
			}).finally(() => {
				tableLoading.value = false;
			});
			const list = result.data;
			for (let i = 0; i < list.length; i++) {
				tableList.value.push(list[i]);
			}
			totalPage.value = result.page;
			total.value = result.total;
			type === "refresh" && uni.stopPullDownRefresh();
		} catch (e) {
			console.log(e);
		}
	}
	const scrolltolower = () => {
		totalPage.value > current.value && loadmore();
	};


	// --------------------------------------------------------------------- 点击tableList item
	// 弹窗展示
	const showConfirmButton = ref(true);
	const showImport = ref(false);
	const deletedItem = ref({});
	function deleted(data) {
		deletedItem.value = data
		showImport.value = true;
	}
	function cancelImport() {
		showImport.value = false;
	}
	async function confirmImport() {
		if (!showConfirmButton.value) {
			return;
		}
		showConfirmButton.value = false;
		await http({
			method: "POST",
			url: `/mes/mesattendancereport/deleteItem/${deletedItem.value?.id}`,
			data: formData,
		}).then((res : any) => {
			if (res.code == 200) {
				uni.$u.toast('删除成功！');
				deletedItem.value = {};
				rest();
				showConfirmButton.value = false;
				showImport.value = false;
			}
		}).finally(() => {
			deletedItem.value = {};
			rest();
			showConfirmButton.value = true;
			showImport.value = false;
			tableList.value = [];
			loadmore("refresh")
		});
	}
	// --------------------------------------------------------------------- 工序
	const rules = ref({
		planNumber: [{
			type: "number",
			required: true,
			max: 10,
			message: "请输入数字",
			trigger: ["blur"],
		},
		{
			// 自定义验证函数，见上说明
			validator: (rule, value, callback) => {
				// 上面有说，返回true表示校验通过，返回false表示不通过
				// uni.$u.test.mobile()就是返回true或者false的
				if (isNaN(parseFloat(value)) && isFinite(value)) {
					callback(new Error("请输入数字"));
				} else if (!/^[+]?\d+?(e[+]?\d+)?$/.test(value)) {
					callback(new Error("请输入数字"));
				} else if (Number(value) <= 0) {
					callback(new Error("请输入大于0的数"));
				} else {
					callback();
				}
			},
			trigger: ['change', 'blur'],
		}
		],
		actualNumber: [{
			type: "number",
			required: true,
			max: 10,
			message: "请输入数字",
			trigger: ["change"],
		},
		{
			// 自定义验证函数，见上说明
			validator: (rule, value, callback) => {
				// 上面有说，返回true表示校验通过，返回false表示不通过
				// uni.$u.test.mobile()就是返回true或者false的
				if (isNaN(parseFloat(value)) && isFinite(value)) {
					callback(new Error("请输入数字"));
				} else if (!/^[+]?\d+?(e[+]?\d+)?$/.test(value)) {
					callback(new Error("请输入数字"));
				} else if (Number(value) <= 0) {
					callback(new Error("请输入大于0的数"));
				} else {
					callback();
				}
			},
			trigger: ['change', 'blur'],
		}
		],
		shiftId: [{
			type: "string",
			required: true,
			message: "请选择班次",
			trigger: ["change"],
		},
		],
	});
	let formData = reactive({
		id: "",
		shiftId: "",
		shiftName: "",
		planNumber: "",
		actualNumber: "",
		reportDate: getTimes(Date.now()),
		reportDateA: getTimes(Date.now()),
	});
	const showImportTemperature = ref(false);
	function lineStoveRecord() {
		showImportTemperature.value = true;
	}
	
	function openTemperature(data) {
		formData = JSON.parse(JSON.stringify(data));
		formData.reportDateA = formData.reportDate;
		showImportTemperature.value = true;
	}
	function rest() {
		formData.reportDate = getTimes(Date.now());
		formData.reportDateA = getTimes(Date.now());
		formData.shiftId = "";
		formData.shiftName = "";
		formData.planNumber = "";
		formData.actualNumber = "";
		formData.id = "";
	}

	function cancelImportTemperature() {
		rest();
		showImportTemperature.value = false;
	}
	const uForm = ref();
	const flag = ref(false)
	function confirmImportTemperature() {
		uForm.value.validate().then(async (valid : any) => {
			if (valid) {
				if (flag.value) {
					return;
				}
				flag.value = true;
				await http({
					method: "POST",
					url: "/mes/mesattendancereport/save",
					data: formData,
				}).then((res : any) => {
					if (res.code == 200) {
						uni.showToast({
							title: "人员出勤填报成功！",
						});
						rest();
						showImportTemperature.value = false;
						flag.value = false;
						tableList.value = [];
						loadmore("refresh")
					}
				}).finally(() => {
					flag.value = false;
				});
			}
		});
	}
	const showReportDate = ref(false);
	function openTimeSelectReportDate() {
		showReportDate.value = true;
		uni.hideKeyboard();
	}
	function timeSelectReportDate1(e) {
		console.log(e);
		formData.reportDateA = e.value;
		formData.reportDate = getTimes(e.value);
		console.log(formData.reportDate);
		showReportDate.value = false;
		formData.shiftId = "";
		formData.shiftName = "";
	}

	//-------------------------------------------------------班次
	//班次选择
	const showShift = ref(false);
	const shiftList = ref([
		[{
			id: "1",
			shiftId: "1",
			shiftName: "A",
		},
		{
			id: "2",
			shiftId: "2",
			shiftName: "B",
		},]
	]);
	const shiftIndex = ref();

	async function getShiftList() {
		await http({
			method: "POST",
			url: "/mes/messhift/getList",
			data: {},
		}).then((res : any) => {
			shiftList.value[0] = res.data
		}).catch((e) => {
			console.log(e)
			uni.$u.toast(e.data.message, 4 * 1000);
		})
	}

	function openPickSelect() {
		showShift.value = true;
	}
	function shiftSelect(e) {
		console.log(e)
		if (e.value.length) {
			formData.shiftId = e.value[0].shiftId;
			formData.shiftName = e.value[0].shiftName;
		} else {
			formData.shiftId = "";
			formData.shiftName = "";
		}
		console.log(formData)
		showShift.value = false;
	}
</script>

<style lang="scss" scoped>
	uni-page-body {
		height: 100%;
		background-color: #fbfbff;
	}

	.search {
		:deep(.u-search__content) {
			box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
		}
	}

	.baseForm {
		background-color: #fbfbff;

		.tab-bar {
			padding: 0 20px;
		}

		.upload-scan {
			padding: $uni-page-padding;
			padding-top: 5px;
			padding-bottom: 5px;
			display: flex;
			align-items: center;

			// box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
			.u-icon {
				margin-left: 8px;
			}
		}

		.u-line {
			padding: 10px 0;
		}
	}

	:deep(.u-textarea__field) {
		text-align: right;
	}

	.list {
		.card {
			margin: $uni-page-padding;
			margin-top: 5px;
			margin-bottom: 4px;
			border-radius: 7px;
			padding: 12px 12px 0px 12px;
			transition: all 300ms ease;
			border: 1px solid #efefef;
			background-color: #fff;

			.card-flex {
				display: flex;
				align-items: flex-start;
			}

			.right {
				flex: 1;
			}

			.title {
				font-size: 14px;
				line-height: 40px;
				height: 40px;
				margin-top: 8px;
				font-weight: bold;
				color: #101010;
				border-top: 1px solid #e5ebff;
			}

			.uni-btn {
				float: right;
				font-size: 12px;
				height: 24px;
				line-height: 24px;
				padding: 0 15px;
				margin-top: 7px;
				font-weight: 400;
			}

			.des {
				font-size: 12px;
				line-height: 20px;
				margin-bottom: 3px;
			}

			.left {
				flex-basis: calc(50% + 10px);
			}
		}
	}

	.record-title {
		display: flex;
		justify-content: space-between;
		margin: 2px 0 2px 0;
		color: $primary-color;

		uni-text:nth-child(1) {
			font-weight: bold;
			font-size: 15px;
		}

		uni-text:nth-child(2) {
			font-weight: bold;
			font-size: 15px;
			min-width: 60px;
			text-align: right;
		}
	}

	.record-item {
		margin: 7px 0 !important;
		color: #8f8e94 !important;
		word-break: break-all;
		font-size: 13px;
	}

	.record-item1 {
		color: #8f8e94 !important;
		word-break: break-all;
		font-size: 13px;
	}

	.record-content .record-item> :first-child {
		min-width: 70px !important;
	}

	:deep(.input-box) {
		// width: calc(100% - 56px);
		width: 100%;
		// border: 0.5px solid #dadbde !important;
		border-radius: 100px;
		height: 32px;
		line-height: 32px;
		box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
		background-color: #fff;

		.u-input {
			pointer-events: none;
			height: 32px;
			line-height: 32px;
			padding-left: 10px !important;
		}

		.uni-input-placeholder {
			color: rgb(144, 147, 153) !important;
			font-size: 14px;
		}

		.u-icon__icon {
			font-size: 22px !important;
			line-height: 22px;
			font-weight: normal;
			top: 0px;
			color: rgb(144, 147, 153) !important;
		}

		image {
			padding: 6px 6px;
			width: 20px;
			height: 20px;
		}
	}

	:deep(.search-btn) {
		width: 32px;
		height: 34px;
		margin-left: 4px;
		border-radius: 4px;
		background-color: transparent;
		border: none;

		.u-button__text {
			color: rgb(96, 98, 102) !important;
		}
	}

	:deep(.searchButton) {
		color: rgb(41, 121, 255);
		font-size: 14px;
		width: 52px !important;
		min-width: 52px !important;
		display: flex;
		justify-content: flex-start;

		.u-icon {
			margin-left: 2px !important;
			font-size: 14px;

			.u-icon__icon {
				font-size: 14px !important;
				line-height: 14px !important;
			}
		}
	}

	:deep(.u-dropdown) {
		flex: none !important;
		width: 52px;

		.u-cell-group__wrapper {
			// border: 1px solid rgb(214, 215, 217);
			// border-radius: 4px;
			border-right: 1px solid rgb(214, 215, 217);
			border-left: 1px solid rgb(214, 215, 217);
		}

		// .u-line { display: none;}
		.u-cell__body {
			padding: 8px 10px !important;
			// border: 1px solid #8f8e94;
		}

		.u-dropdown__content__mask {
			background-color: transparent;
		}
	}

</style>